<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');

class Hm_Order_module extends CI_Module {
    public $data;
    public $sid;
    private $table_order_hotel_goods;
    private $table_hotel_goods;
    private $order_status_array;
    private $pay_status_array;

    public function __construct()
    {
        parent::__construct();
        $this->sid = $GLOBALS['sid'];
        $this->data = $GLOBALS['config'];
        $this->load->model('order.Orderlog_model');
        $this->load->model('order.Orderpaylog_model');
        $this->load->model('order.Ordercontacts_model');
        $this->load->model('order.Orderinfo_model');
        $this->load->model('order.Orderhotel_model');
        $this->load->model('order.Orderhotelgoods_model');
        $this->load->model('order.Orderroom_model');
        $this->load->model('hotel.Hotel_model');
        $this->load->model('order.Ordertourist_model');
        $this->load->model('member.User_model');
        $this->load->model('order.Ordernumberlog_model');

        $this->table_order_hotel_goods = $this->db->dbprefix("order_hotel_goods");
        $this->table_hotel_goods = $this->db->dbprefix("hotel_goods");

        $this->config->load('base');

        $this->order_status_array = $this->config->item('order_status');
        $this->pay_status_array = $this->config->item('pay_status');

        $this->period_price_array = array(
            $GLOBALS['config']['week_unit_price'],
            $GLOBALS['config']['mon_unit_price'],
            $GLOBALS['config']['tue_unit_price'],
            $GLOBALS['config']['wed_unit_price'],
            $GLOBALS['config']['thu_unit_price'],
            $GLOBALS['config']['fri_unit_price'],
            $GLOBALS['config']['sat_unit_price']
        );

        $admin_user_id = $this->session->userdata('admin_user_id');
        if (empty($admin_user_id))  redirect('denglu?type=1');
    }


    /**
     *  订单列表
     */

    public function order_list()
    {

        $where = $this->db->dbprefix("order_info") . ".order_type=1 AND " . $this->db->dbprefix("order_info") . ".sid=$this->sid ";//酒店订单

        $page_config['perpage'] = 15;   //每页条数
        $page_config['part'] = 2;//当前页前后链接数量
        $page_config['url'] = 'order/adminhotel/index';//url
        $page_config['param'] = '';//参数
        $page_config['seg'] = 4; //参数取 index.php之后的段数，默认为3，即index.php/control/function/18 这种形式
        $page_config['nowindex'] = $this->uri->segment($page_config['seg']) ? $this->uri->segment($page_config['seg']) : 1;//当前页
        $page_config['total'] = $this->Orderhotel_model->get_order_count($where);
        $this->load->library('mypageclass');
        $this->mypageclass->initialize($page_config);


        $order_info_fields = format_table_field(array('order_id', 'order_account', 'earnest_account', 'order_sn', 'order_status', 'pay_status', 'cat_type', 'add_time,paid_account,earnest_paid_account'), $this->db->dbprefix("order_info"));
        $contact_fields = format_table_field(array('name as contact_name', 'phone_num', 'wx_nick'), $this->db->dbprefix("order_contacts"));

        $order_hotel_fields = format_table_field(array('number', 'start_date', 'end_date'), $this->db->dbprefix("order_hotel"));

        $fields = $contact_fields . ',' . $order_hotel_fields . ',' . $order_info_fields;
        $result = $this->Orderhotel_model->get_order_list($page_config['perpage'], $page_config['nowindex'], $where, $fields);

        if ($result)
        {
            foreach ($result as $key => $item)
            {
                $order_room_table = $this->db->dbprefix("order_room");
                $hotel_room_table = $this->db->dbprefix("hotel_room");

                $rstr = array();
                $rdate = array();
                $room = $this->Orderroom_model->get_room_info_array("$order_room_table.order_id = {$item['order_id']}", "$hotel_room_table .name,$order_room_table .date ", false, false);

                if ($room)
                {
                    foreach ($room as $index => $value)
                    {
                        $rstr[$index] = $value['name'];
                        $rdate[$index] = fdate($value['date']);
                    }
                }
                $rstr = array_unique($rstr);
                $rdate = array_unique($rdate);

                $result[$key]['rstr'] = !empty($rstr) ? implode(',', $rstr) : '未安排房间';
                $result[$key]['rdate'] = !empty($rdate) ? implode(',', $rdate) : '';


                $result[$key]['past_order_status'] = (strtotime($item['end_date']) < time()) ? true : false;

                $result[$key]['edit_url'] = site_url('hm/order/edit/' . $item['order_id']);


                $result[$key]['order_status_name'] = $this->order_status_array[$item['order_status']];
                $result[$key]['pay_status_name'] = $this->pay_status_array[$item['pay_status']];
                $result[$key]['cat_type_name'] = ($item['cat_type']==1)? '门市订单':'游客订单' ;
                $result[$key]['start_date'] = fdate($item['start_date']) ;
                $result[$key]['end_date'] = fdate($item['end_date']) ;
                $result[$key]['order_account'] =  price_format($item['order_account']) ;



            }
        }


        $this->data['list'] = $result;
        $this->data['add_url'] = site_url('order/adminhotel/add');
        $this->data['common'] = array(
            array(
                'title' => '订单列表',
                'nav'=>'order'
            )
        );


        if($this->input->get_post('is_ajax'))
        {
            echo json_encode($result);
            exit;
        }
        $this->data['nowindex'] = $page_config['nowindex'];

        $this->load->view('default/order_list', $this->data);
    }


    /**
     * 酒店订单编辑页面
     */
    public function edit($order_id)
    {


        //联系人信息
        $this->data['contact_info'] = $this->Ordercontacts_model->get_row(array('order_id' => $order_id));

        //订单基本信息
        $this->data['order_info'] = $this->Orderinfo_model->get_row(array('order_id' => $order_id));

        $hotel_order_info = $this->Orderhotel_model->get_row(array('order_id' => $order_id));
        $this->data['hotel_order_info'] = $hotel_order_info;


        $start = $this->input->get_post('start') ? ($this->input->get_post('start')) : $hotel_order_info['start_date'];
        $end = $this->input->get_post('end') ? ($this->input->get_post('end')) : $hotel_order_info['end_date'];


        if ($start != $hotel_order_info['start_date'] || $end != $hotel_order_info['end_date'])
        {
            $change_check = true;
        }

        //获取订单房间号
        $order_room = array();
        $order_room_market = array();
        $order_room_list = $this->Orderroom_model->get_room_array("order_id = $order_id", "room_id,number");
        if ($order_room_list)
        {
            foreach ($order_room_list as $index => $item)
            {
                $order_room[$index] = $item['room_id'];
                $order_room_market[$item['room_id']] = $item['number']; // room_id 主键 房间入住人数做键值
            }
        }


        $order_room = array_unique($order_room);
        $this->data['order_room'] = $order_room;
        $this->data['order_room_market'] = $order_room_market;



        $order_room_table = $this->db->dbprefix("order_room");
        $hotel_room_table = $this->db->dbprefix("hotel_room");

        $rstr = array();
        $rdate = array();
        $room = $this->Orderroom_model->get_room_info_array("$order_room_table.order_id = {$order_id}", "$hotel_room_table .name,$order_room_table .date ", false, false);

        if ($room)
        {
            foreach ($room as $index => $value)
            {
                $rstr[$index] = $value['name'];
                $rdate[$index] = fdate($value['date']);
            }
        }
        $rstr = array_unique($rstr);
        $rdate = array_unique($rdate);
        $this->data['rstr'] = !empty($rstr) ? implode(',', $rstr) : '未安排房间';
        $this->data['rdate'] = !empty($rdate) ? implode(',', $rdate) : '';

        //房间基本信息
        $room_list = $this->Hotel_model->get_number_list(array('sid' => $this->sid), '1000', 1);
        $locked_data = $this->Orderroom_model->get_locked_room_list($start, $end);
        $this->data['lock_room'] = $locked_data['ids'];
        $this->data['lock_key_date'] = $locked_data['dates'];
        $this->data['room_list'] = $room_list;

        $order_goods_result = $this->Orderhotelgoods_model->get_list(array('order_id' => $order_id));

        //获取订单酒水产品
        $order_drinks = array();


        if ($order_goods_result)
        {
            foreach ($order_goods_result as $index => $item)
            {
                $order_drinks[$item['good_id']] = array(
                    'good_id' => $item['good_id'],
                    'number' => $item['number']
                );
            }
        }

        $this->data['order_drinks'] = $order_drinks;


        //获取订单附加产品
        $order_goods = array();
        if ($order_goods_result)
        {
            foreach ($order_goods_result as $index => $item)
            {
                $order_goods[$item['good_id']] = array(
                    'good_id' => $item['good_id'],
                    'number' => $item['number']
                );
            }
        }

        $this->data['order_goods'] = $order_goods;


        $this->data['member_list'] = $this->User_model->get_member_list("sid = " . $this->sid, 100, 1);

        $this->data['goods_list'] = $this->Hotel_model->get_extend_product_list("sid = " . $this->sid . " and type = 0");


        $this->data['drinks_list'] = $this->Hotel_model->get_extend_product_list("sid = " . $this->sid . " and type = 1");


        $order_room_account = $this->Ordernumberlog_model->calc_order_room_account($order_id, $hotel_order_info['start_date'], $hotel_order_info['end_date'], $hotel_order_info['number']);

        $this->data['numbers_log'] = $this->Ordernumberlog_model->get_list(array('order_id' => $order_id));
        $this->data['form_url'] = site_url('order/adminhotel/edit_save');
        $this->data['edit_status_url'] = site_url('hm/order/edit_status');
        $this->data['index_url'] = site_url('order/adminhotel/index');
        $this->data['current_url'] = site_url('order/adminhotel/edit?id=' . $order_id);
        $this->data['order_room_account'] = $order_room_account;
        $this->data['start'] = $start;
        $this->data['days'] = (strtotime($end) - strtotime($start)) / 24 / 60 / 60;
        $this->data['end'] = $end;

        $conflict_orders = $this->Orderroom_model->get_conflict_orders($order_id, $order_room, $start, $end);
        $this->data['conflict_orders'] = $conflict_orders;
        $this->data['change_check'] = $change_check;
        $this->data['common'] = array(
            array(
                'title' => '订单编辑'
            )
        );
        $this->load->view('default/order_edit', $this->data);
    }


    public function order_edit()
    {

        $order_id = $this->input->post('order_id');
        $igids = $this->input->post('gids');
        $ignums = $this->input->post('gnums');
        $order_account = $this->input->post('order_account');

        $gids = explode(',', $igids);
        $gnums = explode(',', $ignums);

        $order_goods_status = true;
        $upo_res = true;

        // 添加商品
        $go_batch_data = array();

        if ($gids && $gnums)
        {
            foreach ($gids as $index => $gid)
            {
                $go_batch_data[$index] = array(
                    'sid' => $this->sid,
                    'order_id' => $order_id,
                    'good_id' => $gid,
                    'number' => $gnums[$index],
                );
            }
        }


        if (!empty($go_batch_data))
        {
            $this->Orderhotelgoods_model->delete_row(array('order_id' => $order_id));
            $order_goods_status = $this->Orderhotelgoods_model->add_batch($go_batch_data);
        }


        $order_row = $this->Orderinfo_model->get_row(array('order_id' => $order_id), 'order_status,order_account,,room_account');

        if ($order_row['order_account'] != $order_account)
        {
            $order_data ['order_account'] = $order_account;  //修改订单金额

        }

        if (!empty($order_data))
        {
            $upo_res = $this->Orderinfo_model->edit_row($order_data, array('order_id' => $order_id));

        }

        if ($order_goods_status && $upo_res)
        {
            $this->success('保存成功!', 1, true);
        }
        $this->error('保存失败!', 1, true);

    }


    public function add()
    {
        $this->data['form_url'] = site_url('hm/order/book_save');
        $this->data['common'] = array(
            array(
                'title' => '添加订单',
                'nav'=>'add'
            )
        );
        $this->load->view('default/order_add', $this->data);
    }

    public function book_save()
    {


        $start_date = $_POST['start_date'];
        $end_date = $_POST['end_date'];
        @$male_num = intval($_POST['male_num']);
        @$woman_num = intval($_POST['woman_num']);
        @$child_num = intval($_POST['child_num']);
        @$contact_name = trim($_POST['name']);
        @$contact_phone = trim($_POST['phone']);
        @$note = trim($_POST['note']);


        $days = (strtotime($end_date) - strtotime($start_date)) / 24 / 60 / 60;
        $order_account = ($male_num + $woman_num + $child_num) * $days * $this->data['book_unit_price'];

        //订单信息
        $order_data = array(
            'order_sn' => $this->Orderinfo_model->set_order_sn(),
            'order_type' => 1,//酒店订单
            'cat_type' => 1,//手机订单
            'order_account' => $order_account,
            'room_account' => $order_account,
            'earnest_account' => $order_account / 3,
            'order_status' => 2, //酒店需要审核
            'pay_status' => 1,//未支付
            'order_note' => $note,
            'add_time' => date('Y-m-d H:i:s', time()),
            'user_id' => 0,//用户ID
            'admin_user_id' => '0' //管理员ID
        );
        $order_id = $order_return_status = $this->Orderinfo_model->add_row($order_data);

        if ($order_id)
        {
            //联系人信息
            $contact_data = array(
                'order_id' => $order_id,
                'name' => $contact_name,
                'email' => '',
                'phone_num' => $contact_phone,
                'wx_nick' => ''
            );
            $contact_return_status = $this->Ordercontacts_model->add_row($contact_data);

            //订单酒店信息

            $row = array(
                'sid' => $this->sid,
                'order_id' => $order_id,
                'number' => $male_num + $woman_num + $child_num,
                'days' => $days,
                'male_number' => $male_num,
                'woman_number' => $woman_num,
                'child_number' => $child_num,
                'start_date' => $start_date,
                'end_date' => $end_date

            );

            $return_status = $this->Orderhotel_model->add_row($row);


            if ($contact_return_status && $return_status)
            {
                return json_encode(array('status' => '1', 'info' => '提交订单成功!', 'msg' => 'order_fail'));
            }
            else
            {
                return json_encode(array('status' => '0', 'info' => '订单生成失败!', 'msg' => 'order_fail'));
            }
        }
        else
        {
            return json_encode(array('status' => '0', 'info' => '订单生成失败!', 'msg' => 'order_fail'));
        }


    }


    public function edit_status()
    {

        $order_id = $this->input->get_post('order_id');
        $status = $this->input->get_post('status');

        //添加备注信息
        $order_row = $this->Orderinfo_model->get_row(array('order_id' => $order_id), 'order_status,order_account,,room_account');

        $res = true ;
        if($status !== $order_row['order_status'])
        {

            $data = array('order_id' => $order_id, 'order_status' => $status, 'note' => '修改订单状态');

            // 更改订单状态和备注
            $res = $this->Orderinfo_model->translate_order_status($data);

            if($status == 3){

            $res = $this->Orderinfo_model->remove_row(array('order_id' => $order_id)); // 删除订单基础表
            $this->Orderroom_model->delete_row(array('order_id' => $order_id)); // 删除房间库存表
            $this->Ordercontacts_model->remove_row(array('order_id' => $order_id)); // 删除订单联系人表
            $this->Orderhotel_model->remove_row(array('order_id' => $order_id));  // 删除酒店订单表
            }

            $contact_data = $this->Ordercontacts_model->get_row(array('order_id' => $order_id),'phone_num');
            $hotel_order_data = $this->Orderhotel_model->get_row(array('order_id' => $order_id),'start_date');

            // 操作订单已入住 短信通知游客
            if ($status == 5)
            {
                // 通知游客
                $replace = array('sname' => $this->data['company'], 'date' => $hotel_order_data['start_date'],'phone'=>$this->data['notify_num']);
                $this->User_model->_send_sms($contact_data['phone_num'], 'SMS_10860643', $replace);
            }


            // 订单审核通过通知游客支付定金
            if ($status == 2)
            {
                // 通知游客
                $replace = array('sname' => $this->data['company'], 'date' => $hotel_order_data['start_date']);
                $this->User_model->_send_sms($contact_data['phone_num'], 'SMS_10835528', $replace);
            }


            // 操作订单已完成 短信通知游客
            if ($status == 6)
            {
                // 通知游客
                $replace = array('sname' => $this->data['company'], 'date' => $hotel_order_data['start_date'],'phone'=>$this->data['notify_num']);
                $this->User_model->_send_sms($contact_data['phone_num'], 'SMS_10860531', $replace);
            }


        }

        if($res)  $this->success('操作成功!', 1, true);
        $this->error('操作失败!', 1, true);
    }


    /**
     * 房间库存
     * return true/false
     */
    public function room_repertory()
    {
        $start = $this->input->get_post('start') ? $this->input->get_post('start') : date('Y-m-d');
        $end = $this->input->get_post('end') ? $this->input->get_post('end') : date('Y-m-d',strtotime('+1 day'));



        $this->data['room_list'] = $this->Hotel_model->get_number_array(array('sid' => $this->sid));
        $locked_data = $this->Orderroom_model->get_locked_room_list($start, $end);


        $this->data['lock_room'] = $locked_data['ids'];
        $this->data['lock_key_date'] = $locked_data['dates'];
        $this->data['start'] = $start;
        $this->data['end'] = $end;


        foreach ($this->data['room_list'] as $key => $value)
        {
            $order_contacts_res  =array();
            if(in_array($value['id'],$locked_data['ids']))
            {
                $condition = "sid = $this->sid and room_id = {$value['id']} and date between '{$start}' and '{$end}' ";
                $order_ids_res = $this->Orderroom_model->get_room_array($condition, 'order_id');
                if ($order_ids_res)
                {
                    $order_ids = array();

                    foreach ($order_ids_res as $index => $order_ids_re)
                    {
                        $order_ids[$index] = $order_ids_re['order_id'];
                    }
                }
                $where = "order_id in (" . implode(array_unique($order_ids), ',') . ")";
                $order_contacts_res = $this->Ordercontacts_model->get_rows($where, 'name,phone_num');
            }

            $this->data['room_list'][$key]['contact_list'] = $order_contacts_res ;
        }





        $this->data['common'] = array(
            array(
                'title' => '订单编辑',
                'nav'=>'repertory'
            )
        );

        $this->load->view('default/repertory_list',$this->data);
    }
}